package cn.edu.cqvie.atc.sort.impl;

import cn.edu.cqvie.atc.sort.Sort;

import java.util.Comparator;

/**
 * 希尔排序
 *
 * @author Zheng Shaohong
 */
public class ShellSort<T> extends BaseSort<T> {

    public static void main(String[] args) {
        Integer[] arr = new Integer[]{23, 12, 8, 0, 18, 90, 1, 2, 3};

        Sort<Integer> s = new ShellSort<Integer>();
        s.sort(arr, new IntegerComparator());
        s.display(arr);

    }

    /**
     * 排序方法
     */
    public void sort(T[] arr) {
        // 初始化间隔
        int h = 1;
        // 计算最大间隔
        while (h < arr.length / 3) {
            h = h * 3 + 1;
        }
        while (h > 0) {
            // 插入排序
            T tmp = null;
            for (int i = h; i < arr.length; i++) {
                tmp = arr[i];
                int j = i;
                while (j > h - 1 && c.compare(arr[j - h], tmp) >= 0) {
                    arr[j] = arr[j - h];
                    j -= h;
                }
                arr[j] = tmp;
            }
            // 减少间隔
            h = (h - 1) / 3;
        }
    }

    @Override
    public void sort(T[] arr, Comparator<T> c) {
        super.c = c;
        sort(arr);
    }
}
